package com.lowan.device.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lowan.device.config.MqttConfig;
import com.lowan.device.model.DeviceEntity;
import com.lowan.lib.mqtt.LowanMqttCallback;
import com.lowan.lib.mqtt.LowanMqttClient;

/**
 * Title: MqttSubscribe.java
 * <p>
 * 终端设备 mqtt 订阅消息
 *
 * @author y_sp
 * @date 2022 二月
 */
public class MqttSubscribe {

    public MqttSubscribe() {
        /** 客户端初始化 */
        new MqttConfig();
    }

    /**
     * 订阅
     */
    public void subscribe() {

        /** 订阅topic规则 /lowaniot/租户编码/应用标识/产品编码 */
        final String topic = "/lowaniot/${tenantCode}/${appId}/${productId}";
        new Thread(new Runnable() {
            public void run() {
                new LowanMqttClient(topic, new LowanMqttCallback() {
                    public void onMessageArrived(String topic, byte[] payload) {
                        /** 接收到消息后的业务处理 */
                        String message = new String(payload);
                        System.out.println("订阅主题topic : " + topic + "; 订阅消息message : " + message);

                        /** 设备上报数据 */
                        DeviceEntity deviceEntity = JSON.parseObject(message, DeviceEntity.class);
                        JSONObject data = deviceEntity.getData();

                        // Please continue your business ...
                    }
                }).run();
            }
        }).start();
    }

    /**
     * 启动订阅
     */
    public static void main(String[] args) {

        MqttSubscribe mqttSubscribe = new MqttSubscribe();
        mqttSubscribe.subscribe();
    }
}
